package com.ld.shieldsb.common.core.util.notice;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ld.shieldsb.common.core.model.PropertiesModel;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.core.util.JsoupUtil;
import com.ld.shieldsb.common.core.util.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WeChatUtil {
    public static final String E_ERRCODE = "errcode"; // 企业微信错误编码
    public static final String E_ERRMSG = "errmsg"; // 企业微信错误信息
    public static final String E_INVALID_USER = "invaliduser"; // 企业微信未发送成功的用户
    public static final String E_URL_GETTOKEN = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"; // 企业微信获取token的url
    public static final String E_URL_SEND = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s"; // 企业微信未发送通知的url

    public static Result sendEnterpriseWeChatMsg(String sendTo, String msg) {
        // 注意下面参数需要到企业微信中获取
        String corpid = PropertiesModel.CONFIG.getString("notice.ewechat.client-id");
        String corpsecret = PropertiesModel.CONFIG.getString("notice.ewechat.client-secret");
        String agentid = PropertiesModel.CONFIG.getString("notice.ewechat.agent-id");

        Result flag = sendEnterpriseWeChatMsg(corpid, corpsecret, agentid, sendTo, msg);
        return flag;
    }

    /**
     * 发送企业微信信息，参考https://work.weixin.qq.com/api/doc/#90000/90135/90236
     * 
     * @Title sendMsg
     * @author 吕凯
     * @date 2018年12月29日 下午3:27:01
     * @param corpid
     * @param corpsecret
     * @param agentid
     * @param sendTo
     * @param msg
     * @return Result
     */
    public static Result sendEnterpriseWeChatMsg(String corpid, String corpsecret, String agentid, String sendTo, String msg) {
        Result result = new Result();
        result.setSuccess(false);
        result.setMessage("连接异常！");
        String getTokenUrl = String.format(E_URL_GETTOKEN, corpid, corpsecret);
        JSONObject jsonObj = JsoupUtil.getRemoteURLJson(getTokenUrl);
        if (jsonObj != null) {
            Integer errcode = jsonObj.getInteger(E_ERRCODE);
            if (errcode == 0) { // 0是成功
                String accessToken = (String) jsonObj.get("access_token");
                String sendUrl = String.format(E_URL_SEND, accessToken);
                String userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
                Map<String, Object> data = new HashMap<>();
                data.put("touser", sendTo);
                data.put("msgtype", "text");
                data.put("agentid", agentid);
                Map<String, String> contentMap = new HashMap<>();
                contentMap.put("content", msg);
                data.put("text", contentMap);
                data.put("safe", 0);
                JSONObject jsonResult = JsoupUtil.sendJson(data, sendUrl, userAgent, 10000);
                if (jsonResult != null) {
                    result.setData(jsonResult);
                    errcode = jsonResult.getInteger(E_ERRCODE);
                    String errmsg = jsonResult.getString(E_ERRMSG); // 信息
                    String invaliduser = jsonResult.getString(E_INVALID_USER); // 未发送成功的用户
                    result.setMessage(errmsg);
                    if (errcode == 0) { // 0是成功
                        result.setSuccess(true);
                    } else {
                        result.setSuccess(false);
                    }
                    if (StringUtils.isNotEmpty(invaliduser)) {
                        result.setSuccess(false);
                        result.setMessage("发送失败的用户：" + invaliduser);
                    }
                    log.debug(jsonResult + "");
                }
            } else {
                String errmsg = jsonObj.getString(E_ERRMSG); // 信息
                result.setSuccess(false);
                result.setMessage(errmsg);
                // {"errcode":41002,"errmsg":"corpid missing, hint: [1566888599_12_0c7cbc4ed7886d21f534b85b7aafebb3], from ip:
                // 122.4.233.133, more info at https://open.work.weixin.qq.com/devtool/query?e=41002"}
            }
        }
        return result;

    }

}
